<template>
    <div class="banners-container">
        <!-- 搜索表单 -->
        <div class="mb10">
            <SearchForm :searchFields="searchItems" :maxFirstRowItems="3" @search="handleSearch" @reset="handleReset" />
        </div>

        <!-- 操作按钮 -->
        <div class="mb10">
            <div class="table-operations">
                <a-button type="primary" @click="addBanner">
                    <PlusOutlined /> 新增广告
                </a-button>
                <a-button type="primary" danger :disabled="!hasSelected" @click="handleBatchDelete">
                    <DeleteOutlined /> 批量删除
                </a-button>
                <span style="margin-left: 8px;" v-if="hasSelected">
                    已选择 {{ selectedRowKeys.length }} 项
                </span>
            </div>
        </div>

        <!-- 数据列表 -->
        <div class="card-wrap">
            <DataList ref="dataListRef" api="link/getListByPage" deleteApi="link/deleteBanner" :columns="columns"
                :rowSelection="rowSelection" @action="onAction">
                <!-- 自定义列插槽 -->
                <template #title="{ record }">
                    <div class="banner-title">
                        <div class="title-text">{{ record.title }}</div>
                    </div>
                </template>

                <template #cover_img="{ record }">
                    <div class="banner-image">
                        <a-image v-if="record.cover_img" :width="120" :height="60" :src="getImageUrl(record.cover_img)"
                            :preview="true" style="border-radius: 4px; object-fit: cover;" />
                        <span v-else class="no-image">暂无图片</span>
                    </div>
                </template>

                <template #type="{ record }">
                    <div class="banner-type">
                        <a-tag :color="getTypeColor(record.type)">{{ getTypeName(record.type) }}</a-tag>
                    </div>
                </template>

                <template #url="{ record }">
                    <div class="banner-url">
                        <a-tooltip :title="record.url">
                            <span class="url-text">{{ record.url || '-' }}</span>
                        </a-tooltip>
                    </div>
                </template>
                <template #action="{ record }">
                    <a-space>
                        <a-button type="link" size="small" @click="editBanner(record)">
                            编辑
                        </a-button>
                        <a-popconfirm title="确定要删除这个广告吗？" @confirm="handleDelete(record.id)">
                            <a-button type="link" size="small" danger>
                                删除
                            </a-button>
                        </a-popconfirm>
                    </a-space>
                </template>
            </DataList>
        </div>

        <!-- 新增/编辑广告模态框 -->
        <a-modal v-model:open="editModalVisible" :title="editForm.id ? '编辑广告' : '新增广告'" width="600px" @ok="handleSave"
            :confirmLoading="saveLoading">
            <a-form ref="formRef" :model="editForm" :rules="editRules" layout="vertical">
                <a-form-item label="广告标题" name="title">
                    <a-input v-model:value="editForm.title" placeholder="请输入广告标题" />
                </a-form-item>

                <a-form-item label="跳转类型" name="type">
                    <a-select v-model:value="editForm.type" placeholder="请选择跳转类型" @change="handleTypeChange">
                        <a-select-option :value="1">小程序页面</a-select-option>
                        <a-select-option :value="2">外部小程序</a-select-option>
                        <a-select-option :value="3">webview</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="跳转链接" name="url">
                    <a-input v-model:value="editForm.url" :placeholder="getUrlPlaceholder()" />
                </a-form-item>

                <a-form-item v-if="editForm.type === 2" label="外部小程序AppId" name="app_id">
                    <a-input v-model:value="editForm.app_id" placeholder="请输入外部小程序的AppId" />
                </a-form-item>

                <a-form-item label="广告封面" name="cover_img">
                    <div class="custom-upload">
                        <div class="upload-area" @click="triggerFileInput" :class="{ 'has-image': currentImageUrl }">
                            <div v-if="currentImageUrl" class="image-preview">
                                <img :src="getImageUrl(currentImageUrl)" alt="广告封面" />
                                <div class="image-overlay">
                                    <div class="overlay-actions">
                                        <a-button type="text" size="small" @click.stop="handlePreviewImage">
                                            <EyeOutlined />
                                        </a-button>
                                        <a-button type="text" size="small" @click.stop="removeImage">
                                            <DeleteOutlined />
                                        </a-button>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="upload-placeholder">
                                <div class="upload-icon">
                                    <PlusOutlined />
                                </div>
                                <div class="upload-text">点击上传Banner图</div>
                                <div class="upload-hint">建议尺寸: 2:1 比例</div>
                            </div>
                        </div>
                        <input ref="fileInputRef" type="file" accept="image/*" style="display: none"
                            @change="handleFileSelect" />
                        <div v-if="uploading" class="upload-progress">
                            <a-progress :percent="uploadProgress" size="small" />
                        </div>
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- 图片预览模态框 -->
        <a-modal v-model:open="previewVisible" title="图片预览" :footer="null" centered>
            <img :src="previewImageUrl" style="width: 100%; max-height: 500px; object-fit: contain;" />
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DeleteOutlined, PlusOutlined, EyeOutlined } from '@ant-design/icons-vue'
import DataList from '@/components/DataList.vue'
import SearchForm from '@/components/SearchForm.vue'
import { uploadFile } from '@/utils/ossUpload'
import { baseAPI } from '@/api/api.js'

// 获取图片完整URL的函数
const getImageUrl = (url) => {
    if (!url) return ''
    if (url.startsWith('http')) return url

    // 使用环境变量中的OSS地址
    const ossBaseUrl = import.meta.env.VITE_OSS_BASE_URL
    return `${ossBaseUrl}/${url}`
}

// 响应式数据
const dataListRef = ref()
const formRef = ref()
const selectedRowKeys = ref([])
const editModalVisible = ref(false)
const saveLoading = ref(false)
const fileInputRef = ref()
const currentImageUrl = ref('')
const uploading = ref(false)
const uploadProgress = ref(0)
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 编辑表单
const editForm = reactive({
    id: null,
    title: '',
    url: '',
    type: 1,
    app_id: '',
    cover_img: ''
})

// 表单验证规则
const editRules = {
    title: [
        { required: true, message: '请输入广告标题', trigger: 'blur' },
        { max: 10, message: '广告标题不能超过10个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择跳转类型', trigger: 'change' }
    ],
    url: [
        { required: true, message: '请输入跳转链接', trigger: 'blur' },
        { max: 255, message: '跳转链接不能超过255个字符', trigger: 'blur' }
    ],
    app_id: [
        {
            validator: (rule, value) => {
                if (editForm.type === 2 && !value) {
                    return Promise.reject('外部小程序需要填写AppId')
                }
                return Promise.resolve()
            },
            trigger: 'blur'
        }
    ],
    cover_img: [
        { required: true, message: '请上传广告封面', trigger: 'change' }
    ]
}

// 搜索表单配置
const searchItems = ref([
    {
        label: '广告标题',
        prop: 'title',
        type: 'input',
        placeholder: '请输入广告标题'
    },
    {
        label: '创建时间',
        prop: 'date_range',
        type: 'daterange',
        placeholder: ['开始日期', '结束日期']
    }
])

// 表格列配置
const columns = [
    {
        title: '广告标题',
        dataIndex: 'title',
        width: 150,
        slot: true
    },
    {
        title: '广告封面',
        dataIndex: 'cover_img',
        width: 120,
        slot: true
    },
    {
        title: '跳转类型',
        dataIndex: 'type',
        width: 120,
        slot: true
    },
    {
        title: '跳转链接',
        dataIndex: 'url',
        width: 200,
        slot: true
    },
    {
        title: '修改时间',
        dataIndex: 'updated_at',
        width: 180,
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        width: 180,
    },
    {
        title: '操作',
        key: 'action',
        width: 150,
        type: 'action',
        options: [
            { title: '编辑', key: 'edit' },
            { title: '删除', key: 'delete', type: 'delete' }
        ]
    }
]

// 行选择配置
const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (keys) => {
        selectedRowKeys.value = keys
    }
}

// 计算属性
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 方法
const onAction = (item, record) => {
    if (item.key === 'edit') {
        editBanner(record)
    }
}

const handleSearch = (params) => {
    // 处理日期范围
    if (params.date_range && params.date_range.length === 2) {
        params.start_date = params.date_range[0]
        params.end_date = params.date_range[1]
        delete params.date_range
    }

    dataListRef.value.search(params)
}

const handleReset = () => {
    dataListRef.value.reset()
}

const addBanner = () => {
    editForm.id = null
    editForm.title = ''
    editForm.url = ''
    editForm.type = 1
    editForm.app_id = ''
    editForm.cover_img = ''
    currentImageUrl.value = ''
    editModalVisible.value = true
}

const editBanner = (record) => {
    editForm.id = record.id
    editForm.title = record.title
    editForm.url = record.url
    editForm.type = record.type || 1
    editForm.app_id = record.app_id || ''
    editForm.cover_img = record.cover_img
    currentImageUrl.value = record.cover_img || ''
    editModalVisible.value = true
}

// 处理跳转类型变化
const handleTypeChange = (value) => {
    // 当类型不是外部小程序时，清空appId
    if (value !== 2) {
        editForm.app_id = ''
    }
}

// 获取URL输入框占位符
const getUrlPlaceholder = () => {
    switch (editForm.type) {
        case 1:
            return '请输入小程序页面路径，如：/pages/index/index'
        case 2:
            return '请输入外部小程序页面路径，如：/pages/index/index'
        case 3:
            return '请输入网页链接，如：https://www.example.com'
        default:
            return '请输入跳转链接'
    }
}

// 获取跳转类型名称
const getTypeName = (type) => {
    switch (type) {
        case 1:
            return '当前小程序'
        case 2:
            return '外部小程序'
        case 3:
            return 'webview'
        default:
            return '未知类型'
    }
}

// 获取跳转类型颜色
const getTypeColor = (type) => {
    switch (type) {
        case 1:
            return 'blue'
        case 2:
            return 'green'
        case 3:
            return 'orange'
        default:
            return 'default'
    }
}

function handleDelete(id) {
    return baseAPI.post('link/deleteBanner', { id })
        .then(function () {
            message.success('删除成功')
            dataListRef.value.refreshData()
        })
        .catch(function (error) {
            message.error('删除失败：' + error.message)
        })
}

const handleBatchDelete = () => {
    if (selectedRowKeys.value.length === 0) {
        message.warning('请选择要删除的广告')
        return
    }

    Modal.confirm({
        title: '确认删除',
        content: `确定要删除选中的 ${selectedRowKeys.value.length} 个广告吗？`,
        onOk: function () {
            return baseAPI.post('link/batchDeleteBanners', { ids: selectedRowKeys.value })
                .then(function () {
                    message.success('批量删除成功')
                    selectedRowKeys.value = []
                    dataListRef.value.refreshData()
                })
                .catch(function (error) {
                    message.error('批量删除失败：' + error.message)
                })
        }
    })
}

// 触发文件选择
const triggerFileInput = () => {
    fileInputRef.value?.click()
}

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files?.[0]
    if (!file) return

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
        message.error('只能上传图片文件！')
        return
    }

    // 验证文件大小（10MB）
    const maxSize = 10 * 1024 * 1024
    if (file.size > maxSize) {
        message.error('图片大小不能超过10MB！')
        return
    }

    uploading.value = true
    uploadProgress.value = 0

    uploadFile(file).then(function (result) {
        currentImageUrl.value = result.url
        editForm.cover_img = result.url
        message.success('图片上传成功')
    }).catch(function (error) {
        console.error('图片上传失败:', error)
        message.error('图片上传失败：' + error.message)
    }).finally(function () {
        uploading.value = false
        uploadProgress.value = 0
        // 清空文件输入框
        event.target.value = ''
    })
}

// 预览图片
const handlePreviewImage = () => {
    if (currentImageUrl.value) {
        previewImageUrl.value = getImageUrl(currentImageUrl.value)
        previewVisible.value = true
    }
}

// 移除图片
const removeImage = () => {
    currentImageUrl.value = ''
    editForm.cover_img = ''
}

function handleSave() {
    // 验证是否上传了图片
    if (!currentImageUrl.value) {
        message.error('请先上传广告封面')
        return
    }

    formRef.value.validate().then(function () {
        saveLoading.value = true

        baseAPI.post('link/save', editForm).then(res => {
            if (res.code == 200) {
                message.success('保存成功')
                saveLoading.value = false
                editModalVisible.value = false
                dataListRef.value.refreshData()
            }
        })
    })
}

// 生命周期
onMounted(() => {
    // 初始化数据
})
</script>

<style lang="less" scoped>
.banners-container {
    padding: 24px;
}

.banner-title {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.title-text {
    font-weight: 500;
    color: #1890ff;
    cursor: pointer;
}

.banner-image {
    display: flex;
    align-items: center;
}

.no-image {
    color: #999;
    font-size: 12px;
}

.banner-url {
    max-width: 200px;
}

.url-text {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #1890ff;
    cursor: pointer;
}

.table-operations {
    display: flex;
    align-items: center;
    gap: 8px;
}

.image-preview {
    margin-top: 8px;
}

.custom-upload {
    .upload-area {
        width: 240px;
        height: 120px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color 0.3s;

        &:hover {
            border-color: #1890ff;
        }

        &.has-image {
            border: none;
        }
    }

    .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #999;

        .upload-icon {
            font-size: 24px;
            margin-bottom: 8px;
        }

        .upload-text {
            font-size: 12px;
        }

        .upload-hint {
            font-size: 10px;
            color: #999;
            margin-top: 4px;
        }
    }

    .image-preview {
        width: 100%;
        height: 100%;
        position: relative;
        margin: 0;

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 6px;
        }

        .image-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s;
            border-radius: 6px;

            &:hover {
                opacity: 1;
            }
        }

        .overlay-actions {
            display: flex;
            gap: 8px;

            .ant-btn {
                color: white;
                border: none;
                background: transparent;

                &:hover {
                    background: rgba(255, 255, 255, 0.2);
                }
            }
        }
    }

    .upload-progress {
        margin-top: 8px;
    }
}
</style>